package com.saodisheng.util;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * description:
 * jasypt工具类
 *
 * @author 扫地生_saodisheng
 * @date 2022/1/13
 */
public class JasyptUtils {
    /**
     * cryptOr 初始化加密配置
     *
     * @param password password jasypt解密盐
     * @return org.jasypt.encryption.pbe.config.SimpleStringPBEConfig
     * @author saodisheng_liuxingwu
     * @date 2022/1/13
    */
    public static SimpleStringPBEConfig cryptOr(String password) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName(null);
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");

        return config;
    }

    /**
     * encryptPwd
     * jasypt生成加密结果
     *
     * @param password password 配置文件中设置的加密盐
     * @param value value   待加密值
     * @return java.lang.String 加密后的结果
     * @author saodisheng_liuxingwu
     * @date 2022/1/13
    */
    public static String encryptPwd(String password, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(password));
        return encryptOr.encrypt(value);
    }

    /**
     * decyptPwd
     * jasypt解密
     *
     * @param password password
     * @param value value
     * @return java.lang.String
     * @author saodisheng_liuxingwu
     * @date 2022/1/13
    */
    public static String decyptPwd(String password, String value) {
        PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
        encryptOr.setConfig(cryptOr(password));
        return encryptOr.decrypt(value);
    }

    public static void main(String[] args) {
        // 加密、解密
        System.out.println(encryptPwd("1234", "5678"));
        System.out.println(decyptPwd("1234", "LBVdpC0GdOyFLaDyV9O6jqE4mwg71zUd"));
    }
}
